#include "constant.h"
#include "request.h"
#include "fileop.h"
#include "log.h"
#include "utils.h"
int send_buff(const struct request *req, const char *buff,int len);
const char *get_value(const char *key);

int get_html(struct request *req, const char *path)
{
	FILE *file = 0;
	int size_of_file = 0;
	char *buff;
	int status;

	file = fopen(path, "rb");
	if ( 0 == file ) {
		SYS_ERR("fopen");
		return BS_ERROR;
	}

	GET_FILE_SIZE(file, size_of_file);
	if ( !size_of_file) {
		LOG_ERR("size of file %s is zero!", file);
		LEAVE_CLOSE(file, BS_ERROR);
	}

	buff = (char *)malloc(size_of_file + 1);
	if (!buff) {
		SYS_ERR("malloc");
		LEAVE_CLOSE(file, BS_ERROR);
	}

	fread(buff, sizeof(char), size_of_file + 1, file);
	if ( !feof(file) ) {
		SAFE_FREE(buff);
		LEAVE_CLOSE(file, BS_ERROR);
	}
		

	status = send_buff(req, buff, size_of_file);
	SAFE_FREE(buff);
	if (file)
		fclose(file);

	return status;
}


/* no free in this function for req 
* actually no free on req is in all
* follow functions
*/
void get_error_html(struct request *req)
{
	return ;
}


struct url_map {
	const char *key;
	const char *value;
} static url_maps[] = {
	{"/","./html/index.html"},
	{"/Images/chick1.jpg","./Images/chick1.jpg"}
};

const char *get_value(const char *key)
{
	int i ;
	for (i = 0; i < SIZE_OF_ARRAY(url_maps); ++i)
		if ( !strcmp(key, url_maps[i].key) )
			return url_maps[i].value;

	return 0;
}

